package com.ea.common.log;

import com.alibaba.fastjson.JSON;
import com.ea.common.result.Result;
import com.ea.common.utils.HttpContextUtils;
import com.ea.common.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
@Aspect
@Slf4j
public class LogAop {
    @Pointcut("@annotation(com.ea.common.log.LogAnnotation)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        long beginTime = System.currentTimeMillis();
        recordLog(joinPoint);

        Object result = joinPoint.proceed();
        long time = System.currentTimeMillis() - beginTime;
        recordData(result);
        recordTime(time);
        return result;
    }

    private void recordData(Object r) {
        // 只有当返回值是Result类型时才记录数据
        if (r instanceof Result) {
            Result result = (Result) r;
            if (result != null && result.getData() != null) {
                log.info("data:{}", result.getData());
            }
        }
    }

    public void recordLog(ProceedingJoinPoint joinPoint)
    {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        log.info("=============== log start ===============");
        log.info("module: {}", logAnnotation.module());
        log.info("operation: {}", logAnnotation.operation());

        //获得请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method: {}.{}()", className, methodName);

        //请求的参数（过滤掉不能序列化的对象）
        Object[] args = joinPoint.getArgs();
        List<Object> serializableArgs = new ArrayList<>();
        for (Object arg : args) {
            if (arg instanceof HttpServletRequest) {
                serializableArgs.add("[HttpServletRequest]");
            } else if (arg instanceof HttpServletResponse) {
                serializableArgs.add("[HttpServletResponse]");
            } else {
                serializableArgs.add(arg);
            }
        }
        String params = JSON.toJSONString(serializableArgs);
        log.info("params: {}", params);

        //获取请求的ip地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip: {}", IpUtils.getIpAddr(request));
        log.info("proceeding......");
    }

    public void recordTime(long time)
    {
        log.info("execute time: {} ms", time);
        log.info("=============== log end ===============");
    }
}